<?php

namespace app\common\service\auth;

use app\model\Agent;

class AuthOpenService extends AuthBase implements AuthInterface
{

    /** @var Agent $agent */
    protected $agent;

    public function attempt($params)
    {
        $app_key = $params['app_key'] ?? '';

        /** @var Agent $agent */
        $agent = Agent::query()
            ->where('app_key', $app_key)
            ->cache('AuthOpenService' . $app_key, 60)
            ->find();

        if (!$agent) {
            return false;
        }

        $sign = $params['sign'];

        if (isLocal()  || (isTesting() && !empty($params['from_test']))) {
            $this->agent = $agent;
            return true;
        }
        if ($sign != $this->getSign($params, $agent->app_secret)) {
            return false;
        }

        $this->agent = $agent;

        return true;
    }

    public function login($params)
    {

    }

    //代理id
    public function id()
    {
        return !empty($this->agent) ? $this->agent->id : 0;
    }

    /**
     * @ 代理id
     */
    public function agentId()
    {

        return !empty($this->agent) ? $this->agent->id : 0;

    }

    public function user()
    {

    }


    /**
     * 签名方式
     * @param $params
     * @param $appSecret
     * @return string
     */
    public function getSign($params, $appSecret)
    {
        if (isset($params['sign'])) {
            unset($params['sign']);
        }

        ksort($params);

        $sign = '';
        foreach ($params as $k => $v) {
            if ($v === '') {
                continue;
            }
            $sign .= $k . '=' . $v . '&';
        }
        $sign .= 'app_secret=' . $appSecret;

        return strtolower(md5($sign));
    }
}